<?php

declare (strict_types = 1);

namespace app\store\service\user;

use app\common\service\BaseService;
use app\store\model\user\Posts as PostsModel;
use cores\exception\BaseException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;


class Posts extends BaseService
{
    public function getIndex($params):array
    {
        $condition = [];
        if(isset($params['status'])){
            $condition[] = ['status','=',$params['status']];
        }
        $userCondition = [];
        if(!empty($params['search'])){
            $userCondition[] = ['user.nick_name|user.mobile|user.user_id', 'like', "%{$params['search']}%"];
        }
        return (new PostsModel())
            ->with(['user' => function($query){
                $query->withField(['user_id,username,nick_name,avatar_url']);

            }])
            ->where($condition)
            ->hasWhere('user',$userCondition)
            ->paginate($params['limit'] ?? 15)
            ->toArray();
    }

    //审核
    public function check($params):bool
    {
        $posts = (new PostsModel())->where('id',$params['id'])->find();
        if(!$posts){
            throwError('帖子不存在，无法审核');
        }
        if($posts->status != 0){
            throwError('已审核，请勿重复审核');
        }
        $posts->status = $params['status'];
        $posts->save();
        return true;
    }


}
